package com.cnzhy.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * @Author: zhaoyan5
 */
@Slf4j
@WebFilter(filterName = "HttpRequestMdcFilter", urlPatterns = {"/*"})
public class HttpRequestMdcFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MDC.put("user", "zhaoyan");
        HttpServletRequest hrequest = (HttpServletRequest) servletRequest;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
        if (hrequest.getRequestURI().contains("/index") || hrequest.getRequestURI().contains("/hello")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            wrapper.sendRedirect("/login");
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("======init=comment=====");
    }

    @Override
    public void destroy() {
        log.info("======destroy=comment=====");
    }

}
